package com.evl.wxpay.util.paytype.verify;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import com.evl.api.qrcode.service.IWeiXinService;
import com.evl.api.qrcode.vo.TemplateRQ;
import com.evl.common.persistence.model.TrainOrder;
import com.evl.common.persistence.model.WxPayRecord;
import com.evl.core.vo.BaseResultVo;
import com.evl.core.vo.JsonReturnHelper;
import com.evl.dictionaryConfig.DictConfig;
import com.evl.dictionaryConfig.DictConst;
import com.evl.utils.BeanUtils;
import com.evl.utils.DateUtils;
import com.evl.wxpay.util.IWXPay;
import com.evl.wxpay.util.WXPayConstants.SignType;
import com.evl.wxpay.util.WXPayUtil;
import com.evl.wxpay.util.paytype.PayType;
import com.google.gson.JsonObject;

/**
 * 微信小程序支付，下单类型，订单支付
 * @author dangsheng
 *
 */
public class OrderVerify extends Verify{
	
	private Logger log = Logger.getLogger(this.getClass());
	
	/**
	 * 校验数据，添加请求参数
	 */
	@Override
	public Map required(Object obj) throws Exception{
		TrainOrder order = (TrainOrder)obj;
		Map map = new HashMap();
		map.put("body", "车票订单支付");
		map.put("out_trade_no", order.getOrderNo());
		map.put("fee_type", "CNY");
		map.put("total_fee", "1");
		map.put("openid", order.getCreateId()+"");
		
		//增加配置参数
		map.put("spbill_create_ip", "123.12.12.123");
		map.put("trade_type", "JSAPI");
		map.put("notify_url", "https://sit.tyforce.com/traveltickets/payCallBack/wxPayNotify");
		Long timeStamp = new Date().getTime();
		map.put("timeStamp", timeStamp+"");
		//数据校验逻辑
		StringBuffer sb = new StringBuffer();
		if(StringUtils.isEmpty(order.getCreateId())){
			sb.append("openid不能为空;");
		}
		if(StringUtils.isEmpty(order.getId())){
			sb.append("订单id不能为空;");
		}
		if(StringUtils.isEmpty(order.getTotalPrice())){
			sb.append("TotalPrice不能为空;");
		}
		if(sb.length() != 0){
			throw new Exception(sb.toString());
		}
		log.info("支付信息:"+map.toString());
		return map;
	}
	
	/**
	 * 支付日志的必要参数设置，根据传入的对象
	 */
	@Override
	public WxPayRecord logRecord(WxPayRecord wxPayRecord,Object obj){
		log.info("记录支付日志");
		TrainOrder order = (TrainOrder)obj;
		wxPayRecord.setOrderId(order.getId());
		wxPayRecord.setTotalFee(toInt(order.getTotalPrice())*100);
		return wxPayRecord;
	}

	@Override
	public Map request(IWXPay wXPay,PayType payType) throws Exception {
		//调用微信支付的接口方法
		return wXPay.unifiedOrder(payType.getReqData(), payType);
	}

	@Override
	public String getOpenId(PayType payType) {
		return ((TrainOrder)payType.getObj()).getCreateId();
	}

	@Override
	public BaseResultVo sendMessage(PayType payType) {
		if(StringUtils.isEmpty(payType.getFormId())){
			return null;
		}
		
		TrainOrder order = (TrainOrder)payType.getObj();
    	String page=DictConfig.getKey(DictConst.wx_msg_index_page);
    	String template_id = DictConfig.getKey(DictConst.wx_pay_success_msg_temp);
    	
    	String formId = payType.getFormId();
    	
    	JsonObject jsonObject=new JsonObject();
    	
    	JsonObject key1=new JsonObject();
    	key1.addProperty("value", order.getOrderNo());
    	jsonObject.add("keyword1", key1);
    	
    	JsonObject key2=new JsonObject();
   	 	key2.addProperty("value", DateUtils.getSpecifyDate(order.getCreateTime(),DateUtils.FORMAT_YYYY_MM_DD_HH_MM_SS));
   	 	jsonObject.add("keyword2", key2);
   	
		JsonObject key3=new JsonObject();
		key3.addProperty("value", order.getTotalPrice().toString());
		jsonObject.add("keyword3", key3);
	
		JsonObject key4=new JsonObject();
		key4.addProperty("value", "车票");
		jsonObject.add("keyword4", key4);
		
		
		if(!payType.isSucessed()){
			//支付失败
			template_id = DictConfig.getKey("wx_pay_faild_msg_temp");
			JsonObject key5=new JsonObject();
			key5.addProperty("value", payType.getError());
			jsonObject.add("keyword4"+"", key5);
		}
    	
    	TemplateRQ templateRQ=new TemplateRQ();
    	templateRQ.setTouser(payType.getOpenId());
    	templateRQ.setTemplate_id(template_id);
    	templateRQ.setPage(page);
    	templateRQ.setData(jsonObject);
    	templateRQ.setForm_id(formId);
    	log.info("send message ："+templateRQ.toString());
    	IWeiXinService iWeiXinService = BeanUtils.getBean("weiXinServiceImpl");
    	String res=iWeiXinService.sendTemplate(templateRQ);
    	log.info("send message resoult : "+res);
    	return JsonReturnHelper.getSuccessWithData(res);
	}
	
	@Override
	public void complete(PayType payType) {
		Map rsp = payType.getRspData();
		//再次加密唤起支付请求的数据发送给前端
		String timeStamp = payType.getReqData().get("timeStamp").toString();
		rsp.put("timeStamp", timeStamp);
		String appId = strWithNull(rsp.get("appid"));
		String nonceStr = strWithNull(rsp.get("nonce_str"));
		String prepay_id = strWithNull(rsp.get("prepay_id"));
		String signType = "MD5";
		Map map = new HashMap();
		map.put("appId", appId);
		map.put("timeStamp", timeStamp);
		map.put("nonceStr", nonceStr);
		map.put("signType", signType);
		map.put("package", "prepay_id="+prepay_id);
		try {
			//增加paySign参数
			String paySign = WXPayUtil.generateSignature(map, DictConfig.getKey(DictConst.wx_mch_secret), SignType.MD5);
			rsp.put("paySign", paySign);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
